package com.crm.miaohe.controller.authentication;

import com.crm.miaohe.controller.authentication.request.LoginRequest;
import com.crm.miaohe.controller.authentication.request.user.AuthUserQueryRequest;
import com.crm.miaohe.service.AuthenticationService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

@RestController
@RequestMapping("/api/erp/auth")
public class AuthenticationController {

    private final AuthenticationService authenticationService;

    public AuthenticationController(AuthenticationService authenticationService) {
        this.authenticationService = authenticationService;
    }

    @PostMapping("/login")
    public ResponseEntity<OAuth2AccessToken> login(@RequestBody @Valid LoginRequest request, @NotBlank @RequestHeader("x-platform-id") String platform) {
        return ResponseEntity.ok(authenticationService.authenticate(request, platform));
    }

    @PostMapping("/login_encode")
    public ResponseEntity<OAuth2AccessToken> loginEncode(@RequestBody @Valid LoginRequest request, @NotBlank @RequestHeader("x-platform-id") String platform) {
        return ResponseEntity.ok(authenticationService.authenticateEncode(request, platform));
    }

    @PostMapping("/logout")
    public void logout(@RequestHeader("Authorization") @NotBlank String accessToken) {
        authenticationService.logout(accessToken);
    }

    @PostMapping("/checkUser")
    public ResponseEntity<Boolean> checkUser(@RequestBody AuthUserQueryRequest registerRequest) {
        return ResponseEntity.ok(authenticationService.checkUserByUserNameOrPhoneNumber(registerRequest));
    }

    @PostMapping("/refresh_token")
    public ResponseEntity<OAuth2AccessToken> refresh(@RequestHeader("x-refresh-token") @NotBlank String refreshToken) {
        return ResponseEntity.ok(authenticationService.refreshToken(refreshToken));
    }
}
